package com.suyang.syt.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AccessUtil {
	private AccessUtil() {
	}

	/**
	 * 数据库驱动字符串
	 */
	private static String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
	
	/**
	 * 连接URL字符串
	 */
	private static String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=D:/it9000/lcall4/v/db/vr.mdb";

	/**
	 * 获取数据库连接对象
	 * @return 数据库连接对象
	 */
	public static Connection getConnection() {
		Connection connection = null;
		try {
			Class.forName(driver); // 加载驱动
			connection = DriverManager.getConnection(url); // 获得数据库链接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @param connection	数据库链接
	 * @param statement		statement对象
	 * @param resultSet		结果集
	 */
	public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
		// 若结果集不为空，则关闭
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若Statement对象不为空，则关闭
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若数据库连接对象不为空，则关闭
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @param connection		数据库链接
	 * @param preparedStatement	preparedStatement对象
	 * @param resultSet			结果集
	 */
	public static void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
		// 若结果集不为空，则关闭
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若preparedStatement对象不为空，则关闭
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 若数据库连接对象不为空，则关闭
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
